{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"../../img/ods_stickers.jpg\" />"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 决策树和随机森林分析应用"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "本次挑战是关于决策树和随机森林方法的应用练习，首先导入必要的模块。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install pydotplus  # 安装必要模块"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "import warnings\n",
    "from io import StringIO\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import pydotplus\n",
    "import seaborn as sns\n",
    "from IPython.display import SVG\n",
    "from matplotlib import pyplot as plt\n",
    "from sklearn import preprocessing\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.metrics import accuracy_score\n",
    "from sklearn.model_selection import GridSearchCV, cross_val_score\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "from sklearn.tree import DecisionTreeClassifier, export_graphviz\n",
    "\n",
    "%matplotlib inline\n",
    "plt.rcParams[\"figure.figsize\"] = (10, 8)\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 简单示例练习"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "此小节中，我们将通过解决一个简单的示例问题来弄清楚决策树是如何工作的。虽然单颗决策树不太会产生出色的结果，但其他基于相同的思想的高性能算法（如梯度增强和随机森林）往往就威力强大了。这就需要我们先了解简单决策树的工作机制。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来，我们创建一个示例数据集，该数据集表示了 A 会不会和 B 进行第二次约会。而数据集中的特征包括：外貌，口才，酒精消费，以及第一次约会花了多少钱。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 创建示例数据集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建示例数据集，并对数据类别进行独热编码\n",
    "def create_df(dic, feature_list):\n",
    "    out = pd.DataFrame(dic)\n",
    "    out = pd.concat([out, pd.get_dummies(out[feature_list])], axis=1)\n",
    "    out.drop(feature_list, axis=1, inplace=True)\n",
    "    return out\n",
    "\n",
    "\n",
    "# 保证独热编码后的特征在训练和测试数据中同时存在\n",
    "\n",
    "\n",
    "def intersect_features(train, test):\n",
    "    common_feat = list(set(train.keys()) & set(test.keys()))\n",
    "    return train[common_feat], test[common_feat]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "features = [\"Looks\", \"Alcoholic_beverage\", \"Eloquence\", \"Money_spent\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来，我们指定一些训练和测试数据。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 训练数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_train = {}\n",
    "df_train[\"Looks\"] = [\n",
    "    \"handsome\",\n",
    "    \"handsome\",\n",
    "    \"handsome\",\n",
    "    \"repulsive\",\n",
    "    \"repulsive\",\n",
    "    \"repulsive\",\n",
    "    \"handsome\",\n",
    "]\n",
    "df_train[\"Alcoholic_beverage\"] = [\"yes\", \"yes\", \"no\", \"no\", \"yes\", \"yes\", \"yes\"]\n",
    "df_train[\"Eloquence\"] = [\"high\", \"low\", \"average\", \"average\", \"low\", \"high\", \"average\"]\n",
    "df_train[\"Money_spent\"] = [\"lots\", \"little\", \"lots\", \"little\", \"lots\", \"lots\", \"lots\"]\n",
    "df_train[\"Will_go\"] = LabelEncoder().fit_transform([\"+\", \"-\", \"+\", \"-\", \"-\", \"+\", \"+\"])\n",
    "\n",
    "df_train = create_df(df_train, features)\n",
    "df_train"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 测试数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_test = {}\n",
    "df_test[\"Looks\"] = [\"handsome\", \"handsome\", \"repulsive\"]\n",
    "df_test[\"Alcoholic_beverage\"] = [\"no\", \"yes\", \"yes\"]\n",
    "df_test[\"Eloquence\"] = [\"average\", \"high\", \"average\"]\n",
    "df_test[\"Money_spent\"] = [\"lots\", \"little\", \"lots\"]\n",
    "df_test = create_df(df_test, features)\n",
    "df_test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 保证独热编码后的特征在训练和测试数据中同时存在\n",
    "y = df_train[\"Will_go\"]\n",
    "df_train, df_test = intersect_features(train=df_train, test=df_test)\n",
    "df_train"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_test"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<i class=\"fa fa-question-circle\" aria-hidden=\"true\"> 问题：</i>请根据上面的训练数据集在线下用纸和笔手绘一颗基于信息熵的决策树。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "不要跳过此题，一定要自己试一试！"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当然，我们也可以使用 scikit-learn 提供的方法来绘制决策树。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dt = DecisionTreeClassifier(criterion=\"entropy\", random_state=17)\n",
    "dt.fit(df_train, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tree_str = export_graphviz(\n",
    "    dt, feature_names=df_train.columns, out_file=None, filled=True\n",
    ")\n",
    "graph = pydotplus.graph_from_dot_data(tree_str)\n",
    "SVG(graph.create_svg())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 计算熵和信息增益"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来，我们换另外一个例子：假设有 9 个蓝色球和 11 个黄色球。如果球是蓝色，则让球的标签是 1，否则为 0。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "balls = [1 for i in range(9)] + [0 for i in range(11)]  # 生成数据"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src = 'https://doc.shiyanlou.com/courses/uid214893-20190505-1557034726255'>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来将球分成如下两组："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src = 'https://doc.shiyanlou.com/courses/uid214893-20190505-1557034743748'>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 数据分组\n",
    "# 8 蓝色 和 5 黄色\n",
    "balls_left = [1 for i in range(8)] + [0 for i in range(5)]\n",
    "# 1 蓝色 和 6 黄色\n",
    "balls_right = [1 for i in range(1)] + [0 for i in range(6)]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<i class=\"fa fa-question-circle\" aria-hidden=\"true\"> 问题：</i>请根据前面的实验内容实现香农熵计算函数 `entropy()`。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "实现函数时，请结合下一题给出的测试示例，保证测试用例可以执行成功。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<i class=\"fa fa-question-circle\" aria-hidden=\"true\"> 问题：</i>列表 ball_left 给出状态的熵是多少？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<font color='green'><i class=\"fa fa-check-circle-o\" aria-hidden=\"true\"> 期望结果：</i></font>0.961"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<i class=\"fa fa-question-circle\" aria-hidden=\"true\"> 问题：</i>如果有一个 6 面立方体等概率骰子，其熵是多少？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<font color='green'><i class=\"fa fa-check-circle-o\" aria-hidden=\"true\"> 期望结果：</i></font>2.585"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来，请实现信息增益的计算函数 `information_gain(root, left, right)`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<i class=\"fa fa-question-circle\" aria-hidden=\"true\"> 问题：</i>将初始数据集拆分为 balls_left 和 balls_right 后的信息增益是多少？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<font color='green'><i class=\"fa fa-check-circle-o\" aria-hidden=\"true\"> 期望结果：</i></font>0.161"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来，我们尝试实现基于信息增益划分函数 `best_feature_to_split`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def best_feature_to_split(X, y):\n",
    "    \"\"\"信息增益用于特征分割\"\"\"\n",
    "    out = []\n",
    "    for i in X.columns:\n",
    "        out.append(information_gain(y, y[X[i] == 0], y[X[i] == 1]))\n",
    "    return out"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后，通过递归调用 `best_feature_to_split` 实现一个简单的树构建策略，并输出每一步的熵变化。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def btree(X, y):\n",
    "    clf = best_feature_to_split(X, y)\n",
    "    param = clf.index(max(clf))\n",
    "    ly = y[X.iloc[:, param] == 0]\n",
    "    ry = y[X.iloc[:, param] == 1]\n",
    "    print(\"Column_\" + str(param) + \" N/Y?\")\n",
    "    print(\"Entropy: \", entropy(ly), entropy(ry))\n",
    "    print(\"N count:\", ly.count(), \"/\", \"Y count:\", ry.count())\n",
    "    if entropy(ly) != 0:\n",
    "        left = X[X.iloc[:, param] == 0]\n",
    "        btree(left, ly)\n",
    "    if entropy(ry) != 0:\n",
    "        right = X[X.iloc[:, param] == 1]\n",
    "        btree(right, ry)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "best_feature_to_split(df_train, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "btree(df_train, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 构建 Adult 数据集决策树"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[<i class=\"fa fa-external-link-square\" aria-hidden=\"true\"> UCI Adult</i>](http://archive.ics.uci.edu/ml/machine-learning-databases/adult) 人口收入普查数据集前面已经使用过了，其具有以下一些特征："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Age – 连续数值特征\n",
    "- Workclass –  连续数值特征\n",
    "- fnlwgt – 连续数值特征\n",
    "- Education –  类别特征\n",
    "- Education_Num – 连续数值特征\n",
    "- Martial_Status –  类别特征\n",
    "- Occupation –  类别特征\n",
    "- Relationship – 类别特征\n",
    "- Race – 类别特征\n",
    "- Sex – 类别特征\n",
    "- Capital_Gain – 连续数值特征\n",
    "- Capital_Loss – 连续数值特征\n",
    "- Hours_per_week – 连续数值特征\n",
    "- Country – 类别特征"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Target – 收入水平，二元分类目标值"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来，我们加载并读取该数据集："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_train = pd.read_csv(\"../../data/adult_train.csv\", sep=\";\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_train.tail()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_test = pd.read_csv(\"../../data/adult_test.csv\", sep=\";\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_test.tail()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后，对数据集进行一些必要的清洗。同时，将目标值转换为 0，1 二元数值。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 移除测试集中的错误数据\n",
    "data_test = data_test[\n",
    "    (data_test[\"Target\"] == \" >50K.\") | (data_test[\"Target\"] == \" <=50K.\")\n",
    "]\n",
    "\n",
    "# 将目标编码为 0 和 1\n",
    "data_train.loc[data_train[\"Target\"] == \" <=50K\", \"Target\"] = 0\n",
    "data_train.loc[data_train[\"Target\"] == \" >50K\", \"Target\"] = 1\n",
    "\n",
    "data_test.loc[data_test[\"Target\"] == \" <=50K.\", \"Target\"] = 0\n",
    "data_test.loc[data_test[\"Target\"] == \" >50K.\", \"Target\"] = 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "输出测试数据概览表，查看特征和目标值的各项统计指标。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_test.describe(include=\"all\").T"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来，查看训练数据集目标分布计数，同时绘制各项特征的关联分布图像。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_train[\"Target\"].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(25, 15))\n",
    "cols = 5\n",
    "rows = np.ceil(float(data_train.shape[1]) / cols)\n",
    "for i, column in enumerate(data_train.columns):\n",
    "    ax = fig.add_subplot(rows, cols, i + 1)\n",
    "    ax.set_title(column)\n",
    "    if data_train.dtypes[column] == np.object:\n",
    "        data_train[column].value_counts().plot(kind=\"bar\", axes=ax)\n",
    "    else:\n",
    "        data_train[column].hist(axes=ax)\n",
    "        plt.xticks(rotation=\"vertical\")\n",
    "plt.subplots_adjust(hspace=0.7, wspace=0.2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "进一步分析之前，需要检查数据的类型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_train.dtypes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_test.dtypes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以看的测试数据中，年龄 Age 是 object 类型，我们需要修复其为整数类型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_test[\"Age\"] = data_test[\"Age\"].astype(int)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "与此同时，我们将测试数据中浮点类型特征全部处理成整数类型，以便与训练数据对应。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_test[\"fnlwgt\"] = data_test[\"fnlwgt\"].astype(int)\n",
    "data_test[\"Education_Num\"] = data_test[\"Education_Num\"].astype(int)\n",
    "data_test[\"Capital_Gain\"] = data_test[\"Capital_Gain\"].astype(int)\n",
    "data_test[\"Capital_Loss\"] = data_test[\"Capital_Loss\"].astype(int)\n",
    "data_test[\"Hours_per_week\"] = data_test[\"Hours_per_week\"].astype(int)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里还需要继续对数据预处理，首先区分数据集中的类别和连续特征。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 从数据集中选择类别和连续特征变量\n",
    "categorical_columns = [\n",
    "    c for c in data_train.columns if data_train[c].dtype.name == \"object\"\n",
    "]\n",
    "numerical_columns = [\n",
    "    c for c in data_train.columns if data_train[c].dtype.name != \"object\"\n",
    "]\n",
    "\n",
    "print(\"categorical_columns:\", categorical_columns)\n",
    "print(\"numerical_columns:\", numerical_columns)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后，对连续特征使用中位数对缺失数据进行填充，而类别特征则使用众数进行填充。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 填充缺失数据\n",
    "for c in categorical_columns:\n",
    "    data_train[c].fillna(data_train[c].mode(), inplace=True)\n",
    "    data_test[c].fillna(data_train[c].mode(), inplace=True)\n",
    "\n",
    "for c in numerical_columns:\n",
    "    data_train[c].fillna(data_train[c].median(), inplace=True)\n",
    "    data_test[c].fillna(data_train[c].median(), inplace=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来，我们需要对类别特征进行独热编码，以保证数据集特征全部为数值类型方便后续传入模型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_train = pd.concat(\n",
    "    [data_train[numerical_columns], pd.get_dummies(data_train[categorical_columns])],\n",
    "    axis=1,\n",
    ")\n",
    "\n",
    "data_test = pd.concat(\n",
    "    [data_test[numerical_columns], pd.get_dummies(data_test[categorical_columns])],\n",
    "    axis=1,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "set(data_train.columns) - set(data_test.columns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_train.shape, data_test.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "独热编码之后发现测试数据中没有 Holland，为了与训练数据对应，这里需要创建零值特征进行补齐。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_test[\"Country_ Holand-Netherlands\"] = 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "set(data_train.columns) - set(data_test.columns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_train.head(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_test.head(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train = data_train.drop([\"Target\"], axis=1)\n",
    "y_train = data_train[\"Target\"]\n",
    "\n",
    "X_test = data_test.drop([\"Target\"], axis=1)\n",
    "y_test = data_test[\"Target\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 建立默认参数决策树模型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来，使用训练数据创建一个决策树分类器。挑战规定 `max_depth=3`，`random_state=17`。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<i class=\"fa fa-question-circle\" aria-hidden=\"true\"> 问题：</i>按挑战要求构建决策树，并输出其在测试集上的准确度？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<font color='green'><i class=\"fa fa-check-circle-o\" aria-hidden=\"true\"> 期望结果：</i></font>0.845"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 对决策树模型进行调参"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<i class=\"fa fa-question-circle\" aria-hidden=\"true\"> 问题：</i>使用 GridSearchCV 网格搜索对决策树进行调参并返回最佳参数。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "挑战规定，决策树参数 `random_state = 17`，GridSearchCV 参数 `cv=5`，并对 `max_depth` 参数在 $[8, 10]$ 范围进行网格搜索。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<i class=\"fa fa-question-circle\" aria-hidden=\"true\"> 问题：</i>构建上面最佳参数决策树，并输出其在测试集上的准确度？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<font color='green'><i class=\"fa fa-check-circle-o\" aria-hidden=\"true\"> 期望结果：</i></font>0.847"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 建立随机森林分类模型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "和上面建立决策树相似，可以利用 scikit-learn 提供的随机森林算法建立相应的分类预测模型。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<i class=\"fa fa-question-circle\" aria-hidden=\"true\"> 问题：</i>构建 RandomForestClassifier 随机森林分类器。挑战规定参数 `n_estimators=100` 且 `random_state=17`，其余默认。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "输出在测试集上的分类预测准确度。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<font color='green'><i class=\"fa fa-check-circle-o\" aria-hidden=\"true\"> 期望结果：</i></font>0.858"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"background-color: #e6e6e6; margin-bottom: 10px; padding: 1%; border: 1px solid #ccc; border-radius: 6px;text-align: center;\"><a href=\"https://nbviewer.jupyter.org/github/shiyanlou/mlcourse-answers/tree/master/\" title=\"挑战参考答案\"><i class=\"fa fa-file-code-o\" aria-hidden=\"true\"> 查看挑战参考答案</i></a></div>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
